package com.bdilab.iot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/31 19:34
 * 计算权限
 */
@Configuration
public class PermissionEvaluatorImpl implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        if(!(permission instanceof String))
            return false;

        UserDetails user = (UserDetails) authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        List<String> list = new ArrayList<>();
        for (GrantedAuthority authority : authorities){
            String authName = authority.getAuthority();
            if(authName.equals("超级管理员"))
                return true;
            list.add(authName);
        }
        return list.contains((String) permission);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
